package com.mikao.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * http请求切面
 * <p>打印所有接口的请求参数以及相应的返回值</p>
 *
 * @author KennyDavid
 */
@Order(1)
@Slf4j
@Aspect
@Component
public class HttpAop {
    @Pointcut("execution(* com.mikao.controller.*Controller.*(..))")
    public void controllerPointcut() {
    }

    @Before(value = "controllerPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("=====================Request start=======================");
        log.info("request   url : " + request.getRequestURL().toString());
        log.info("class_method  : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("method    name: " + request.getMethod());
        log.info("platform      : " + request.getHeader("platform"));
        if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod())) {
            for (Object arg : joinPoint.getArgs()) {
                if (arg instanceof BeanPropertyBindingResult) {
                    continue;
                }
                log.info("request params: " + JSON.toJSONString(arg));
            }
        } else {
            log.info("request params: " + request.getQueryString());
        }
    }

    @AfterReturning(pointcut = "controllerPointcut()", returning = "obj")
    public void after(Object obj) {
        if (ObjectUtils.isEmpty(obj)) {
            log.info("response  data: null");
        } else {
            log.info("response  data: " + JSON.toJSONString(obj));
        }
        log.info("======================Request end========================");
    }
}
